import axios from 'axios'
import type {AxiosInstance , AxiosRequestConfig , AxiosResponse} from 'axios'
import type {HYRequestInterceptors , HYRequestConfig} from './type'

import { ElLoading, ILoadingInstance } from 'element-plus'

class HYRequest {
  instance: AxiosInstance
  interceptors?: HYRequestInterceptors
  showLoading?: boolean
  loading?: ILoadingInstance

  constructor(config: HYRequestConfig){
    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading ?? true

    //从config中取出的拦截器是对应的实例的拦截器
    //  请求拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    //响应拦截器
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    //添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        console.log('所有实例都有，请求成功')
        //是否显示加载动画
        if(this.showLoading) {
          this.loading = ElLoading.service({
            lock:true,
            text:'正在请求数据...',
            background:'rgba(0,0,0,0.5)'
          })
        }
        return config
      },
      (err) => {
        console.log('所有实例都有，请求失败')
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        console.log('所有实例都有，响应成功',res)
        //将loading移除
        this.loading?.close()
        return res.data
      },
      (err) => {
        console.log('所有实例都有，响应失败')
        return err
      }
    )
  }

  request<T = any>(config: HYRequestConfig<T>): Promise<T> {
   return new Promise((resolve,reject) => {
      // 单个请求拦截
    if(config.interceptors?.requestInterceptor) {
      config = config.interceptors.requestInterceptor(config)
    }
    if(config.showLoading === false) {
      this.showLoading = config.showLoading
    }
    this.instance.request<any,T>(config).then(res => {
      if(config.interceptors?.responseInterceptor) {
        res = config.interceptors.responseInterceptor(res)
      }
      // console.log(res)
      resolve(res)
      //将showLoading设置为true,这样不会影响下一个请求
      this.showLoading = true
    })
    .catch((err) => {
      //将showLoading设置为true,这样不会影响下一个请求
      this.showLoading = true
      // return err
      reject(err)
    })
   })
  }

  get<T = any>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({...config,method:'GET'})
  }
  post<T = any>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({...config,method:'POST'})
  }
  delete<T = any>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({...config,method:'DELETE'})
  }
  patch<T = any>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({...config,method:'PATCH'})
  }
}

export default HYRequest
